package cn.itcast.oa.view.action;

import java.util.HashSet;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.oa.base.BaseAction;
import cn.itcast.oa.domain.Privilege;
import cn.itcast.oa.domain.Role;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;


@Controller
@Scope("prototype")
public class RoleAction extends BaseAction<Role> implements ModelDriven<Role>{
	
	
	private static final long serialVersionUID = 1L;
	
	private Long[] privilegeIds;

	

	public Long[] getPrivilegeIds() {
		return privilegeIds;
	}

	public void setPrivilegeIds(Long[] privilegeIds) {
		this.privilegeIds = privilegeIds;
	}

	/**列表*/
	public String list() throws Exception {
		List<Role> roleList=roleService.findAll();
		ActionContext.getContext().put("roleList", roleList);
		
		return "list";
	}
	
	/**删除*/
	public String delete() throws Exception {
		
		roleService.delete(model.getId());
		return "tolist";
	}
	
	/**添加页面*/
	public String addUI() throws Exception {
		
		return "saveUI";
	}
	
	/**添加*/
	public String add() throws Exception {
		Role role = new Role();
		role.setName(model.getName());
		role.setDescription(model.getDescription());
		
		
		roleService.save(role);
		return "tolist";
	}
		
	
	/**修改页面*/
	public String editUI() throws Exception {
		Role role = roleService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(role);
		
	
		return "saveUI";
	}
	
	/**修改*/  
	public String edit() throws Exception {
		Role role = roleService.getById(model.getId());
		role.setName(model.getName());
		role.setDescription(model.getDescription());
		roleService.update(role);
		return "tolist";
	}

	/**设置权限页面*/
	public String setPrivilegeUI() throws Exception {
		//准备回显的数据
		Role role = roleService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(role);
		
		if(role.getPrivileges() != null){
			int index=0;
			privilegeIds = new Long[role.getPrivileges().size()];
			for(Privilege priv:role.getPrivileges()){
				privilegeIds[index++] = priv.getId();
			}
		}
		
		//准备权限数据
		List<Privilege> privilegesList = privilegeService.findAll();
		ActionContext.getContext().put("privilegesList", privilegesList);
		return "setPrivilegeUI";
	}
	
	/**设置权限*/  
	public String setPrivilege() throws Exception {
		//1.从数据库中取出源对象
		Role role = roleService.getById(model.getId());
		//2.设置要修改的属性
		List<Privilege> privileges = privilegeService.getByIds(privilegeIds);
		role.setPrivileges(new HashSet<Privilege>(privileges));
		//3.更新到数据库中
		roleService.update(role);
		return "tolist";
	}
	

}
